package com.jyw.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.activity.CouponActivity;
import com.jyw.activity.OrderActivity;
import com.jyw.activity.OrderPaiedActivity;
import com.jyw.activity.OrderPayActivity;
import com.jyw.activity.OrdersOverActivity;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Order;
import com.jyw.utils.DimenUtils;
import com.victor.loading.rotate.RotateLoading;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/1
 */

public class OrderFragment extends BaseFragment implements View.OnClickListener {
    private View mContentView, vNone;
    private SwipeRefreshLayout layoutSwipe;
    private RecyclerView recycler;
    private TextView tvOver;
    private RotateLoading rotateLoading;

    private OrdersAdapter mAdapter;


    public static OrderFragment newInstance() {
        return new OrderFragment();
    }

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return mContentView = LayoutInflater.from(getActivity()).inflate(R.layout.fgt_order, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        vNone = mContentView.findViewById(R.id.v_none);
        layoutSwipe = (SwipeRefreshLayout) mContentView.findViewById(R.id.layout_swipe);
        recycler = (RecyclerView) mContentView.findViewById(R.id.recycler);
        tvOver = (TextView) mContentView.findViewById(R.id.tv_over);
        rotateLoading = (RotateLoading) mContentView.findViewById(R.id.rotateloading);
        tvOver.setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycler.addItemDecoration(new SpacesItemDecoration(DimenUtils.dip2px(getActivity(), 0f),
                DimenUtils.dip2px(getActivity(), 4f)));
        recycler.setAdapter(mAdapter = new OrdersAdapter(null));

        if (getPrefs().getString("phone", "").equals("")) {
            vNone.setVisibility(View.VISIBLE);
        } else {
            loadData();
        }

        layoutSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_over:
                startActivity(new Intent(getActivity(), OrdersOverActivity.class));
                break;
        }
    }

    class OrdersAdapter extends RecyclerView.Adapter<OrdersAdapter.OrdersHolder> {
        private List<Order> data;

        OrdersAdapter(List<Order> data) {
            this.data = data;
        }

        void swapData(List<Order> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }

        @SuppressLint("InflateParams")
        @Override
        public OrdersHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new OrdersHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_orders, null));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(OrdersHolder holder, final int position) {
            holder.tvClass.setText(data.get(position).getcLass());
            final String state = data.get(position).getState();
            if (data.get(position).getIs_pay().equals("0")) {
                if (state.equals("1")) {
                    holder.tvState0.setText("已接单");
                    holder.tvState1.setText("已接单");
                    holder.tvCancel.setText("取消订单");
                } else if (state.equals("2")) {
                    holder.tvState0.setText("待支付");
                    holder.tvState1.setText("待支付");
                    holder.tvCancel.setText("去支付");
                }
            } else {
                holder.tvState0.setText("已支付");
                holder.tvState1.setText("已支付");
                holder.tvCancel.setText("查看订单");
            }
            holder.tvOrderId.setText("订单编号： " + data.get(position).getOrder_id());
            holder.tvTime.setText("取件时间： " + data.get(position).getService_time());
            holder.view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (data.get(position).getIs_pay().equals("0")) {
                        if (state.equals("1")) {
                            Intent intent = new Intent(getActivity(), OrderActivity.class);
                            intent.putExtra("order_id", data.get(position).getId());
                            startActivity(intent);
                        } else if (state.equals("2")) {
                            /*Intent intent = new Intent(getActivity(), OrderPayActivity.class);
                            intent.putExtra("order_id", data.get(position).getId());
                            startActivity(intent);*/
                            goThroughCouponOrNot(data, position);
                        }
                    } else {
                        Intent intent = new Intent(getActivity(), OrderPaiedActivity.class);
                        intent.putExtra("order_id", data.get(position).getId());
                        startActivity(intent);
                    }

                }
            });

            holder.tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (data.get(position).getIs_pay().equals("0")) {
                        if (state.equals("1")) {
                            final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle("提醒")
                                    .setMessage("是否取消订单?")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            cancelOrder(data.get(position).getId());
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).setCancelable(false).create();
                            dialog.show();
                        } else if (state.equals("2")) {
                            goThroughCouponOrNot(data, position);
                        }
                    } else {
                        Intent intent = new Intent(getActivity(), OrderPaiedActivity.class);
                        intent.putExtra("order_id", data.get(position).getId());
                        startActivity(intent);
                    }
                }
            });
        }

        private void goThroughCouponOrNot(final List<Order> data, final int position) {
            Request request = new Request.Builder().
                    url(Server.GET_COUPON + "?phone_data=" + getPrefs().getString("phone", "")).
                    build();
            OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        org.json.JSONArray arr = new org.json.JSONArray(response.body().string());
                        if (arr.length() == 0) {
                            Intent intent = new Intent(getActivity(), OrderPayActivity.class);
                            intent.putExtra("order_id", data.get(position).getId());
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), CouponActivity.class);
                            intent.putExtra("order_id", data.get(position).getId());
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        private void cancelOrder(String id) {
            Request request = new Request.Builder().
                    url(Server.CANCEL_ORDER + "?id_data=" + id).
                    build();
            OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            loadData();
                        }
                    }.execute();
                }
            });
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        class OrdersHolder extends RecyclerView.ViewHolder {
            View view;
            ImageView ivClass;
            TextView tvClass, tvState0, tvState1, tvOrderId, tvTime, tvCancel;

            OrdersHolder(View itemView) {
                super(itemView);
                this.view = itemView;
                ivClass = (ImageView) itemView.findViewById(R.id.iv_class);
                tvClass = (TextView) itemView.findViewById(R.id.tv_class);
                tvState0 = (TextView) itemView.findViewById(R.id.tv_state0);
                tvState1 = (TextView) itemView.findViewById(R.id.tv_state1);
                tvOrderId = (TextView) itemView.findViewById(R.id.tv_order_id);
                tvTime = (TextView) itemView.findViewById(R.id.tv_time);
                tvCancel = (TextView) itemView.findViewById(R.id.tv_cancel);
            }
        }
    }

    private void loadData() {
        rotateLoading.start();
        Request request = new Request.Builder().
                url(Server.GET_NOT_SUCC_ORDER + "?phone_data=" + getPrefs().getString("phone", "")
                        + "&state_data=0&path_data=1").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONArray arr;
                final List<Order> orders = new ArrayList<>();
                try {
                    arr = new JSONArray(response.body().string());
                    if (arr.length() == 0) {
                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                vNone.setVisibility(View.VISIBLE);
                                rotateLoading.stop();
                                layoutSwipe.setRefreshing(false);
                            }
                        }.execute();
                    } else {
                        Gson gson = new Gson();
                        for (int i = 0; i < arr.length(); i++) {
                            Order order = gson.fromJson(arr.get(i).toString(), Order.class);
                            JSONObject json = new JSONObject(arr.get(i).toString());
                            order.setcLass(json.getString("class"));
                            orders.add(order);
                        }

                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                vNone.setVisibility(View.GONE);
                                layoutSwipe.setRefreshing(false);
                                rotateLoading.stop();
                                mAdapter.swapData(orders);
                            }
                        }.execute();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int leftRight;
        private int topBottom;

        SpacesItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }
    }
}
